use crate::common::{parse_sort_fields, AppState, PaginatedResponse, Response, SortDirection};
use crate::error::AppError;
use crate::models::message::Message;
use crate::vo::message::{MessageReq, MessageRes};
use crate::vo::ValidatedJson;
use anyhow::Context;
use axum::extract::{Query, State};
use axum::response::IntoResponse;
use std::collections::HashMap;
use std::sync::Arc;
use tracing::info;
use tracing::log::warn;

pub async fn create_message(
    State(app_state): State<Arc<AppState>>,
    ValidatedJson(message): ValidatedJson<MessageReq>,
) -> Result<impl IntoResponse, AppError> {
    let user = app_state
        .user
        .lock()
        .unwrap()
        .clone()
        .context("user not found")?;
    let mut message_dtp: Message = message.try_into()?;
    message_dtp.user_id = user.id as i32;
    message_dtp.create(&app_state.pool).await?;
    let users = &app_state.users;
    let user_ids = vec![1, 2, 3];

    for user_id in user_ids {
        if let Some(tx) = users.get(&user_id) {
            info!("Sending notification to user {}", user_id);
            if let Err(e) = tx.send(Arc::new(crate::common::AppEvent::NewMessage {
                data: message_dtp.content.clone(),
            })) {
                warn!("Failed to send notification to user {user_id}: {e}");
            }
        }
    }
    Ok(Response::ok("abc"))
}

pub async fn message_list(
    State(app_state): State<Arc<AppState>>,
    Query(params): Query<HashMap<String, String>>,
) -> Result<Response<PaginatedResponse<MessageRes>>, AppError> {
    let page = params
        .get("page")
        .unwrap_or(&"1".to_string())
        .parse::<i32>()
        .unwrap_or(1);
    let size = params
        .get("limit")
        .unwrap_or(&"10".to_string())
        .parse::<i32>()
        .unwrap_or(10);

    let offset = (page - 1) * size;

    let mut query_string = r#"
        SELECT id, name, price, created_at
        FROM products
    "#
    .to_string();

    let sort_fields = parse_sort_fields(None);

    // 添加 ORDER BY 子句
    if !sort_fields.is_empty() {
        query_string.push_str(" ORDER BY ");

        for (i, field) in sort_fields.iter().enumerate() {
            if i > 0 {
                query_string.push_str(", ");
            }

            query_string.push_str(field.name.as_str());

            match field.direction {
                SortDirection::Ascending => query_string.push_str(" ASC"),
                SortDirection::Descending => query_string.push_str(" DESC"),
            }
        }
    }
    let total_count = Message::count_by_chat_id(1, &app_state.pool).await?;

    // 计算总页数
    let total_pages = ((total_count as f64) / (size as f64)).ceil() as i32;

    let message_list = Message::list_by_chat_id(1, offset, size, &app_state.pool).await?;

    let message_list: Vec<MessageRes> = message_list
        .into_iter()
        .map(|msg: Message| msg.into())
        .collect::<Vec<MessageRes>>();

    Ok(Response::ok(PaginatedResponse::<MessageRes> {
        items: message_list,
        current_page: page,
        per_page: size,
        total_items: total_count as i64,
        total_pages,
    }))
}
